package com.yushu.common.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.yushu.common.execption.CgException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**动态数据源
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static Map<Object, Object> targetDataSources = new HashMap<>();

    public static Map<Object, Object> getTargetDataSources() {
        return targetDataSources;
    }

    /**
     * 设置当前数据源
     *
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        logger.info("Current DataSource is [{}]", DynamicDataSourceContextHolder.getDataSourceKey());
        return DynamicDataSourceContextHolder.getDataSourceKey();
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        DynamicRoutingDataSource.targetDataSources = targetDataSources;
    }

    /**
     * 是否存在当前key的 DataSource
     *
     * @param key
     * @return 存在返回 true, 不存在返回 false
     */
    public static boolean isExistDataSource(String key) {
        return targetDataSources.containsKey(key);
    }


    private void getConnection(Map<String, String> map) throws SQLException {
        Connection connection = null;
        // 排除连接不上的错误
        try {
            Class.forName(map.get("driverClassName"));
            connection = DriverManager.getConnection(map.get("url"), map.get("username"), map.get("password"));
        } catch (Exception e) {
            throw new CgException(e.getMessage());
        } finally {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        }
    }

    /**
     * 动态增加数据源
     *
     * @param database 数据源属性
     * @return
     */
    /*public synchronized boolean addDataSource(ServerDatabase database ) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("driverClassName", "com.mysql.jdbc.Driver");
            map.put("url", database.getDbUrl());
            map.put("username", database.getDbUserName());
            map.put("password", database.getDbPassword());
            map.put("database", database.getId());

            getConnection(map);
            DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(map);
            druidDataSource.init();

            String databaseId = database.getId();//获取要添加的数据库名

            Map<Object, Object> targetMap = DynamicRoutingDataSource.targetDataSources;
            if (targetMap.containsKey(databaseId)) {
                targetMap.remove(databaseId);
            }
            targetMap.put(databaseId, druidDataSource);
            this.afterPropertiesSet();
            logger.info("dataSource [{}] 已经添加", databaseId);


        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }*/


    /**
     * 动态删除数据源
     *
     * @param map 数据源属性
     * @return
     */
    public synchronized boolean removeDataSource(Map<String, String> map) {
        try {
            getConnection(map);
            String database = map.get("database");//获取要添加的数据库名
            DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(map);
            druidDataSource.init();
            Map<Object, Object> targetMap = DynamicRoutingDataSource.targetDataSources;
            if (targetMap.containsKey(database)) {
                targetMap.remove(database);
            }
            targetMap.put(database, druidDataSource);
            this.afterPropertiesSet();
            logger.info("dataSource [{}] 已经删除", database);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }

}

